package jdkproxy;

import RpcExsample.HelloServiceImpl;
import com.zjut.SimpleRPC.core.dto.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * Created by Ryan on 2016/11/25.
 */
public class JDKProxy {

    private String A = "invoking";


    @SuppressWarnings("unchecked")
    public <T> T create(Class<?> interfaceClass) {
        return (T) Proxy.newProxyInstance(
                interfaceClass.getClassLoader(),
                new Class<?>[]{interfaceClass},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
                        request.setRequestId(UUID.randomUUID().toString());
                        request.setClassName(method.getDeclaringClass().getName());
                        request.setMethodName(method.getName());
                        request.setParameterTypes(method.getParameterTypes());
                        request.setParameters(args);
                        System.out.println(A);

                        String s = "";
                        for (Object arg : args) {
                            s += arg.toString();
                        }
                        if (s.equals("Exception")) {
                            Object object= method.invoke(new HelloServiceImpl(), args);
//                            throw new Exception("Exception");
                        }

                        return "JDKProxy:" + method.getName() + " " + s;
                    }
                }
        );
    }

    public static void main(String[] args) {

        HelloService helloService = new JDKProxy().create(HelloService.class);
        System.out.println("return:" + helloService.hello("arg1"));
        System.out.println("return:" + helloService.hello2("arg1", "arg2"));

        try {
            helloService.hello("Exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
